/**
 * 
 */
package org.acsis.covoiturage.frontend.actions;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.acsis.covoiturage.frontend.application.SVC;
import org.acsis.covoiturage.frontend.forms.*;
import org.acsis.covoiturage.services.ITrajetServices;
import org.acsis.covoiturage.shared.IClient;
import org.acsis.covoiturage.shared.ITrajet;
import org.acsis.covoiturage.shared.IUtilisateur;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * @author Abdellah
 *
 */
public class AjoutAction extends Action {

	/* (non-Javadoc)
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		ITrajetServices trajetServices = SVC.create(ITrajetServices.class);
		String date = ((AjoutForm)form).getDate();
//		String heure = ((AjoutForm)form).getHeure();
		double prixPlace = Double.parseDouble(((AjoutForm)form).getPrixPlace());
		short nbrPlaces = Short.parseShort(((AjoutForm)form).getNbrPlaces());
		String villeDepart = ((AjoutForm)form).getVilleDepart();
		String villeArrive= ((AjoutForm)form).getVilleArrive();
		Date dateDepart = (new SimpleDateFormat("dd/MM/yyyy")).parse(date);
		HttpSession session = request.getSession();
		IUtilisateur utilisateur = (IUtilisateur) session.getAttribute("user");
		IClient client=utilisateur.getPersonne();
		
		ITrajet trajet= trajetServices.ajouterTrajet(dateDepart, client.getIdClient(), villeDepart, villeArrive, nbrPlaces, prixPlace);
		if (trajet!=null) {
			return mapping.findForward("success");
		} else {
			ActionErrors errors = new ActionErrors();
			errors.add("ajoutEchec",new ActionMessage("erreur.ajoutEchec"));
			saveErrors(request, errors);
			return mapping.findForward("failed");
		}
	}

}
